package com.boot.app.blog.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boot.api.ApiResult;
import com.boot.app.blog.domain.BlogCategory;
import com.boot.app.blog.service.IBlogCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("blog/category")
public class BlogCategoryController {

    private IBlogCategoryService blogCategoryService;

    @Autowired
    public BlogCategoryController(
        IBlogCategoryService blogCategoryService
    ){
        this.blogCategoryService = blogCategoryService;
    }

    @GetMapping("{id}")
    public ApiResult<BlogCategory> getBlogCategory(@PathVariable("id") long id){
        BlogCategory blogCategory = blogCategoryService.getById(id);
        return ApiResult.success(blogCategory);
    }

    @GetMapping("list")
    public ApiResult<List<BlogCategory>> getBlogCategoryList(BlogCategory blogCategory){
        LambdaQueryWrapper<BlogCategory> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(blogCategory.getCategoryName())) queryWrapper.like(BlogCategory::getCategoryName, blogCategory.getCategoryName());
        if(blogCategory.getStatus() != null) queryWrapper.eq(BlogCategory::getStatus, blogCategory.getStatus());
        List<BlogCategory> blogCategoryList = blogCategoryService.list(queryWrapper);
        return ApiResult.success(blogCategoryList);
    }

    @GetMapping("list/{parentId}")
    public ApiResult<List<BlogCategory>> getBlogCategoryListByParentId(@PathVariable Long parentId, BlogCategory blogCategory){
        LambdaQueryWrapper<BlogCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlogCategory::getParentId, parentId);
        List<BlogCategory> blogCategoryList = blogCategoryService.list(queryWrapper);
        return ApiResult.success(blogCategoryList);
    }

    @PostMapping()
    public ApiResult<?> postAndPutBlogCategory(@RequestBody BlogCategory blogCategory){
        boolean isLeaf = blogCategory.getParentId() == 0 ? false : true;
        blogCategory.setIsLeaf(isLeaf);
        blogCategoryService.saveOrUpdate(blogCategory);
        return ApiResult.success();
    }

    @DeleteMapping("{id}")
    public ApiResult<?> deleteBlogCategory(@PathVariable("id") long id){
        blogCategoryService.removeBlogCategoryById(id);
        return ApiResult.success();
    }

}
